using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OA.BLL
{
    public class LoginUser
    {
        /// <summary>
        /// 在线用户
        /// </summary>
        public class OnLineManager
        {
            /// <summary>
            /// 登陆用户
            /// </summary>
            public string UserName { get; set; }

            /// <summary>
            /// 会话标识符
            /// </summary>
            public string SessionID { get; set; }

            /// <summary>
            /// 是否踢出
            /// </summary>
            public bool IsKick { get; set; }
        }

        static LoginUser()
        {
            OnLineManagers = new List<OnLineManager>();
        }
       

        /// <summary>
        /// 当前登陆用户
        /// </summary>
        public static Model.Manager LoginManager
        {
            get
            {
                var context = System.Web.HttpContext.Current;
                var ret = context.Session[Common.Keys.SessionLoginManager] as Model.Manager;
                return ret;
            }
            set
            {
                var context = System.Web.HttpContext.Current;
                context.Session[Common.Keys.SessionLoginManager] = value;
            }
        }

        /// <summary>
        /// 当前全部在线的用户
        /// </summary>
        public static List<OnLineManager> OnLineManagers { get; set; }


        #region 方法

        public static Model.Manager GetManagerFromCookies()
        {
            Model.Manager model = null;
            var username = Common.Utils.GetCookie(Common.Keys.CookieLoginUserName);
            var password = Common.Utils.GetCookie(Common.Keys.CookieLoginPassword);
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                username = Common.Encrypt.AES.Decode(username);
                password = Common.Encrypt.AES.Decode(password);
                model = new Model.Manager()
                {
                    UserName = username,
                    Password = password
                }; 
            }
            return model;
        }

        public static void SetManagerToCookies(Model.Manager value)
        {
            if (value != null)
            {
                Common.Utils.WriteCookie(Common.Keys.CookieLoginUserName, Common.Encrypt.AES.Encode(value.UserName));
                Common.Utils.WriteCookie(Common.Keys.CookieLoginPassword, Common.Encrypt.AES.Encode(value.Password));
            }
            else
            {
                Common.Utils.WriteCookie(Common.Keys.CookieLoginUserName, null, -1);
                Common.Utils.WriteCookie(Common.Keys.CookieLoginPassword, null, -1);
            }
        }

        /// <summary>
        /// 踢除在线用户
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static Common.Result RemoveOnlineManager(string userName)
        {
            Common.Result ret = new Common.Result(false, 0, null);
            /*
            if (userName == LoginManager.UserName)
            {
                ret.message = "不能将当前登陆账号踢出";
                return ret;
            }*/
            int cnt = 0;
            foreach (var i in BLL.LoginUser.OnLineManagers)
            {
                if (i.IsKick == false && i.UserName == userName)
                {
                    i.IsKick = true;
                    cnt++;
                }
            }
            ret = new Common.Result(true, cnt, "下线成功");
            return ret;
        }

        /// <summary>
        /// 检查用户是否在线
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool IsOnLine(string userName)
        {
            return OnLineManagers.Any(r => r.IsKick == false && r.UserName == userName);
        }

        /// <summary>
        /// 是否登陆
        /// </summary>
        /// <returns></returns>
        public static bool IsLogin()
        {
            var context = System.Web.HttpContext.Current;
            var kick = OnLineManagers.FirstOrDefault(r => r.IsKick == true && r.SessionID == context.Session.SessionID);
            if (kick != null)   //当前用户被踢下线
            {
                LoginOut();
                return false;
            }
            if (LoginManager == null)
            {
                var user = GetManagerFromCookies();
                if (user != null)
                {
                    LoginByMd5(user.UserName, user.Password);
                }
            }
            return LoginManager != null;
        }

        /// <summary>
        /// 退出登陆
        /// </summary>
        public static void LoginOut()
        {
            var context = System.Web.HttpContext.Current;
            context.Session.Abandon();
            LoginManager = null;
            SetManagerToCookies(LoginManager);
        }

        public static Common.Result  Login(string userName, string password)
        {
            return LoginByMd5(userName, Common.Encrypt.MD5.MD5_32(password));
        }

        public static Common.Result LoginByMd5(string userName, string md5Password)
        {
            var ret = new BLL.Manager().ValidateUserByMd5(userName, md5Password);
            if (ret.success == false) return ret;
            var mode = ret.data as Model.Manager;
            var config = BLL.SystemConfig.LoadConfig();

            if (config.Feature.RepeatLogin == 3) //不允许重复登陆
            {
                if (LoginUser.IsOnLine(mode.UserName))
                {
                    ret.success = false;
                    ret.count = 5;
                    ret.message = "当前用户已经登陆，不允许重复登陆";
                    return ret;
                }
            }
            LoginUser.LoginManager = mode;
            SetManagerToCookies(mode);
            var context = System.Web.HttpContext.Current;
            lock (OnLineManagers)
            {
                #region 记录在线用户session
                bool isfind = false;
                for (var i = 0; i < OnLineManagers.Count; i++)
                {
                    var user = OnLineManagers[i];
                    if (user.SessionID == context.Session.SessionID)
                    {
                        user.UserName = mode.UserName;
                        user.IsKick = false;
                        isfind = true;
                        break;
                    }
                }
                if (!isfind)
                {
                    OnLineManagers.Add(new OnLineManager()
                    {
                        UserName = mode.UserName,
                        SessionID = context.Session.SessionID,
                        IsKick = false
                    });
                }
                #endregion

                if (config.Feature.RepeatLogin == 1)  //踢出别的用户
                {
                    foreach (var r in OnLineManagers)
                    {
                        if (r.UserName == mode.UserName && r.SessionID != context.Session.SessionID)
                        {
                            r.IsKick = true;
                        }
                    }
                }
            }
            ret.success = true;
            ret.message = "登陆成功";
            return ret;
        }
        #endregion
    }
}
